package imwallet.dichen.com.library.framework;

import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.ColorInt;
import android.support.annotation.DrawableRes;
import android.support.annotation.MenuRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.support.v7.widget.Toolbar;
import android.text.InputType;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.LinearLayout;

import com.squareup.leakcanary.RefWatcher;

import imwallet.dichen.com.library.app.App;
import imwallet.dichen.com.library.bean.User;
import imwallet.dichen.com.library.constant.Constant;
import imwallet.dichen.com.library.utils.ACache;
import imwallet.dichen.com.library.utils.LogUtils;
import imwallet.dichen.com.library.utils.SoftHideKeyBoardHelper;
import imwallet.dichen.com.library.widget.DefaultToolbar;
import imwallet.dichen.com.library.widget.LoadingDialog;
import imwallet.dichen.com.library.widget.LoadingView;

/**
 *
 * @author Administrator
 * @date 2018/5/28
 */

public abstract class BaseFragment extends Fragment implements RouterActivity.OnBackListener {
    public final String TAG = getClass().getName();
    private LoadingDialog mLoadingDialog;
    protected DefaultToolbar mToolbar;
    private LinearLayout mContentView;
    private LoadingView mLoadingView;
    private Lifecycle mLifecycle;
    private User mUser;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if(mLifecycle != null) {
            mLifecycle.onCreate(TAG);
            if(App.get().isDebug()) {
                LogUtils.e(TAG, "---onCreate---");
            }
        }
    }

    @Nullable
    @Override
    final public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        if(mContentView == null) {
            mContentView = new LinearLayout(getActivity());
            ViewGroup.MarginLayoutParams layoutParams = new ViewGroup
                    .MarginLayoutParams(ViewGroup.MarginLayoutParams.MATCH_PARENT,
                    ViewGroup.MarginLayoutParams.MATCH_PARENT);
            mContentView.setLayoutParams(layoutParams);
            mContentView.setOrientation(LinearLayout.VERTICAL);
        }
        mContentView.removeAllViews();
        if(showToolbar()) {
            mToolbar = new DefaultToolbar(getActivity());
            mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onNavigationClick();
                }
            });
            mContentView.addView(mToolbar);
        }
        View view = createView(inflater, container, savedInstanceState);
        if(view != null) {
            ViewGroup.MarginLayoutParams params = new ViewGroup.MarginLayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            view.setLayoutParams(params);
            initView(view);
            mContentView.addView(view);
        }
        SoftHideKeyBoardHelper.assistActivity(getActivity());
        setTransparentBar();
        return mContentView;
    }

    /**
     * 配置状态栏
     */
    private void setTransparentBar() {
        Window window = getActivity().getWindow();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            //透明状态栏
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }

    /**
     * 获取状态栏高度
     *
     * @param context
     * @return
     */
    protected int getStatusBarHeight(Context context) {
        int result = 0;
        int resourceId = context.getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            result = context.getResources().getDimensionPixelSize(resourceId);
        }
        return result;
    }

    /**
     * 创建fragment布局
     *
     * @param inflater
     * @param container
     * @param savedInstanceState
     * @return
     */
    public abstract View createView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState);

    public void onNavigationClick() {

    }

    public void pushFragment(Class<? extends Fragment> fragmentClass) {
        pushFragment(fragmentClass, null);
    }

    public void pushFragment(Class<? extends Fragment> fragmentClass, Bundle bundle) {
        pushFragment(fragmentClass, bundle, true);
    }

    /**
     * 打开fragment
     *
     * @param tagFragment 需要跳转的fragment
     * @param data 传递的参数
     * @param isAddToBackStack 是否需要添加到回退栈
     */
    public void pushFragment(Class<? extends Fragment> tagFragment, Bundle data, Boolean isAddToBackStack) {
        if(getActivity() != null && getActivity() instanceof BaseActivity) {
            ((BaseActivity)getActivity()).pushFragment(tagFragment, data, isAddToBackStack);
        }
    }

    public void pop() {
        if(getActivity() != null && getActivity() instanceof BaseActivity) {
            ((BaseActivity)getActivity()).onBack();
        }
    }

    public void switchToFragment(Class<? extends Fragment> tagFragment) {
        if(getActivity() != null && getActivity() instanceof BaseActivity) {
            ((BaseActivity)getActivity()).switchFragment(tagFragment);
        }
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        if (getActivity() != null && getActivity() instanceof BaseActivity) {
            ((RouterActivity)getActivity()).setOnBackListener(this);
        }
        if(mLifecycle != null) {
            mLifecycle.onActivityCreated(TAG);
            if(App.get().isDebug()) {
                LogUtils.e(TAG, "---onActivityCreated---");
            }
        }
        initData();
        initListener();
    }

    protected void initView(View view) {

    }

    protected void initData() {

    }

    protected void initListener() {

    }

    public boolean showToolbar() {
        return false;
    }

    @Override
    public boolean intercept() {
        return showToolbar();
    }

    @Override
    public void onBack() {
        ((RouterActivity)getActivity()).pop();
    }

    /**
     * 设置toolbar 背景颜色
     *
     * @param color
     */
    public void setToolbarBackground(@ColorInt int color) {
        if(mToolbar != null) {
            mToolbar.setBackgroundColor(color);
        }
    }

    final protected void setNavigationIcon(@DrawableRes int resId) {
        if(mToolbar != null) {
            mToolbar.setNavigationIcon(resId);
        }
    }

    public void setTitle(String title) {
        if(mToolbar !=null && !TextUtils.isEmpty(title)) {
            mToolbar.setTitle(title);
        }
    }

    public void showBack(boolean isShow) {
        if(mToolbar != null) {
            if(isShow) {
                mToolbar.getNavigationImage().setVisibility(View.VISIBLE);
            } else {
                mToolbar.getNavigationImage().setVisibility(View.GONE);
            }
        }
    }

    public void inflateMenu(@MenuRes int resId) {
        if(mToolbar != null && resId > 0) {
            mToolbar.inflateMenu(resId);
            if(mToolbar.getMenu() != null) {
                mToolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
                    @Override
                    public boolean onMenuItemClick(MenuItem item) {
                        onMenuClick(item.getActionView(), item.getItemId());
                        return true;
                    }
                });
            }
        }
    }

    public void setMenuTitle(String text) {
        if(!TextUtils.isEmpty(text) && mToolbar != null) {
            mToolbar.setMenuText(text);
            if(mToolbar.getMenuView() != null) {
                mToolbar.getMenuView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onMenuClick(view, view.getId());
                    }
                });
            }
        }
    }

    public void setMenuImage(@DrawableRes int resId) {
        if(mToolbar != null && resId > 0) {
            mToolbar.setMenuImage(resId);
            if(mToolbar.getMenuView() != null) {
                mToolbar.getMenuView().setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        onMenuClick(view, view.getId());
                    }
                });
            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if(mLifecycle != null) {
            mLifecycle.onPause(TAG);
            if(App.get().isDebug()) {
                LogUtils.e(TAG, "---onPause---");
            }
        }
    }

    /**
     * 显示加载布局隐藏其他布局
     */
    public void showLoadingView() {
        if(mLoadingView == null) {
            mLoadingView = new LoadingView(getActivity());
        }
        int index;
        if(mToolbar != null) {
            index = 1;
        } else {
            index = 0;
        }
        for(int i = index; i < mContentView.getChildCount(); i ++) {
            mContentView.getChildAt(i).setVisibility(View.GONE);
        }
        mContentView.addView(mLoadingView, index);
    }

    /**
     * 隐藏加载布局
     */
    public void hideLoadingView() {
        if(mLoadingView == null) {
            return;
        }
        mContentView.removeView(mLoadingView);
        mLoadingView = null;
        for(int i = 0; i < mContentView.getChildCount(); i ++) {
            mContentView.getChildAt(i).setVisibility(View.VISIBLE);
        }
    }

    public void onMenuClick(View view, int id) {

    }

    public void setLifecycle(Lifecycle lifecycle) {
        mLifecycle = lifecycle;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (getActivity() != null && getActivity() instanceof BaseActivity) {
            ((RouterActivity)getActivity()).setOnBackListener(null);
        }
        if(mLifecycle != null) {
            mLifecycle.onDestory(TAG);
            if(App.get().isDebug()) {
                LogUtils.e(TAG, "---onDestroy---");
            }
        }
        mLifecycle = null;
//        RefWatcher refWatcher = App.getRefWatcher(getActivity());
//        refWatcher.watch(this);
    }

    /**
     * 跳转到App设置页面修改权限
     */
    protected void gotoSetting() {
        Intent localIntent = new Intent();
        localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
        localIntent.setData(Uri.fromParts("package", getActivity().getPackageName(), null));
        startActivity(localIntent);
    }

    /**
     * 检测是否登录
     *
     * @return
     */
    final protected boolean checkLogin() {
        mUser = (User) ACache.get(getActivity()).getAsObject(Constant.Cache.KEY_USER);
        if(mUser != null) {
            return true;
        }
        return false;
    }

    /**
     * 切换密码显示和隐藏
     *
     * @param isShow
     * @param view
     */
    final protected void switchPassword(boolean isShow, EditText view) {
        if (isShow){
            // 输入为密码且可见
            view.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
        }else {
            // 设置文本类密码（默认不可见），这两个属性必须同时设置
            view.setInputType(InputType.TYPE_TEXT_VARIATION_PASSWORD | InputType.TYPE_CLASS_TEXT);
        }
    }

    protected void showLoadingDialog() {
        showLoadingDialog("");
    }

    protected void showLoadingDialog(String msg) {
        if(mLoadingDialog == null && getActivity() != null) {
            mLoadingDialog = new LoadingDialog(getActivity());
        }
        if(!TextUtils.isEmpty(msg)) {
            mLoadingDialog.setMessage(msg);
        }
        mLoadingDialog.dismiss();
        if(getActivity() != null && !getActivity().isFinishing()) {
            mLoadingDialog.show();
        }
    }

    protected void dismissLoadingDialog() {
        if(mLoadingDialog != null) {
            mLoadingDialog.dismiss();
        }
    }

}
